package CommentApi.Output;

import CommentApi.Comments.ClassComment;
import CommentApi.Comments.MethodComment;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class DefaultTxTOutput implements CommentOutput{
    private final FileWriter fileWriter;

    public DefaultTxTOutput(String fileName) throws IOException {
        fileWriter = new FileWriter(fileName, true);
    }

    @Override
    public void out(List<ControllerInfo> list) {
        try(fileWriter) {
            for (ControllerInfo controllerInfo : list) {
                fileWriter.write(classDesc(controllerInfo.getControllerClass()));
                fileWriter.write("\n");
                for (UriInfo uriInfo : controllerInfo.getUriInfoList()) {
                    fileWriter.write(uriDesc(uriInfo));
                    fileWriter.write("\n\n");
                }
                fileWriter.write("\n");
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }



    private String classDesc(ClassComment classComment){
        String classDesc = "该模块的描述为%s";
        return String.format(classDesc, classComment.getClassComment());
    }

    private String uriDesc(UriInfo uriInfo){
        final StringJoiner resString = new StringJoiner("\n");
        String uriDesc = "uri为%s,支持的方法为:%s\nheader必须包含的为:%s,支持的请求格式为:%s,返回数据格式为:%s\nuri描述为:%s";
        String paramDesc = "参数为%s,参数描述:%s";
        String returnDesc = "返回值描述为:%s";
        String otherDesc = "额外描述:%s";
        MethodComment comment = uriInfo.getMethodComment();

        uriDesc = String.format(uriDesc,getDesc(uriInfo.getUris()),getDesc(uriInfo.getRequestMethod()),getDesc(uriInfo.getHeaders()),getDesc(uriInfo.getConsumes()),getDesc(uriInfo.getProduces()),comment.getMethodComment());

        final StringJoiner paramDescJoiner = new StringJoiner("\n");
        comment.getParamComment().forEach((name,desc)->paramDescJoiner.add(String.format(paramDesc, name,desc)));

        returnDesc = String.format(returnDesc, comment.getReturnDesc());

        otherDesc = String.format(otherDesc, Optional.ofNullable(comment.getOtherDesc()).orElse("无"));

        resString.add(uriDesc);
        resString.add(paramDescJoiner.length() == 0 ? "此uri无参" :paramDescJoiner.toString());
        resString.add(returnDesc);
        resString.add(otherDesc);

        return resString.toString();
    }
    private String getDesc(Object[] objects){
        if (objects.length == 0){
            if (objects.getClass().getComponentType().equals(RequestMethod.class)){
                return "任意方法";
            }
            return "无";
        }else {
            return Arrays.toString(objects);
        }
    }
}
